import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_tutorial/app/routes/app_pages.dart';

class BalanceMiddleware extends GetMiddleware {
  @override
  int? priority = 0;

  BalanceMiddleware({required this.priority});

  @override
  RouteSettings? redirect(String? route) {
    print('==: BalanceMiddleware');

    double balance = 12.0; // 用户余额
    double vipPrice = 10; // 会员价
    if (balance < vipPrice && route != Routes.MINE+Routes.RECHARGE) {
      Future.delayed(
        Duration(seconds: 1), 
        () => Get.snackbar(
          '提示', '账户余额不足',
          snackPosition: SnackPosition.BOTTOM
        )
      );
      return RouteSettings(name: Routes.MINE+Routes.RECHARGE);
    } else {
      return null;
    }
  }

  @override
  GetPage? onPageCalled(GetPage? page) {
    print("》》》 Page ${page?.name} called");
    return page;
  }

  @override
  List<Bindings>? onBindingsStart(List<Bindings>? bindings) {
    // 绑定初始化之前，该函数被调用,
    // bindings = [OtherBinding()];
    // return bindings;
  }

  @override
  GetPageBuilder? onPageBuildStart(GetPageBuilder? page) {
    // 页面构建之前被调用
    print('》》》onPageBuildStart ${page.toString()} are ready');
    return page;
  }

  @override
  Widget onPageBuilt(Widget page) {
    // 页面构建完成
    print('》》》onPageBuilt ${page.toStringShort()} will be showed');
    return page;
  }

  @override
  void onPageDispose() {
    // 页面释放
    print('》》》PageDisposed');
  }
}